/*
 * MainWindow.java
 *
 */
package x2rel.qMap;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import org.jdesktop.application.Action;
import x2rel.qMap.core.Core;
import x2rel.qMap.logger.Logging;

public class MainWindow extends javax.swing.JFrame {
    
    private final String path;
    private File xAlgFile;
    private File equivFile;
    private Core program;
    private Thread tProgram;

    /** Creates new form MainWindow */
    public MainWindow() {
        initComponents();
        
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        path = System.getProperty("user.dir");
        
        Logging.getInstance().log("Aplicação iniciada.");
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        fieldXmlAlgPath = new javax.swing.JTextField();
        btnLoadXmlAlg = new javax.swing.JButton();
        btnLoadOnt = new javax.swing.JButton();
        fieldOntPath = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnGenRAlg = new javax.swing.JButton();
        btnGenSql = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFile = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        menuLoadOnt = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        menuGenRelAlg = new javax.swing.JMenuItem();
        menuGenSql = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JPopupMenu.Separator();
        menuExit = new javax.swing.JMenuItem();
        menuHelp = new javax.swing.JMenu();
        menuAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("QMap :: Query Mapping");

        jPanel1.setBackground(new java.awt.Color(250, 250, 250));

        jLabel1.setText("XQuery Álgebra:");

        fieldXmlAlgPath.setEditable(false);
        fieldXmlAlgPath.setFocusable(false);
        fieldXmlAlgPath.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fieldXmlAlgPathMouseClicked(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(MainWindow.class, this);
        btnLoadXmlAlg.setAction(actionMap.get("loadXqAlgAction")); // NOI18N

        btnLoadOnt.setAction(actionMap.get("loadOntAction")); // NOI18N

        fieldOntPath.setEditable(false);
        fieldOntPath.setFocusable(false);
        fieldOntPath.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fieldOntPathMouseClicked(evt);
            }
        });

        jLabel2.setText("Equivalências:");

        btnGenRAlg.setText("Gerar álgebra relacional");
        btnGenRAlg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenRAlgActionPerformed(evt);
            }
        });

        btnGenSql.setText("Gerar script SQL");
        btnGenSql.setEnabled(false);
        btnGenSql.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenSqlActionPerformed(evt);
            }
        });

        txtLog.setColumns(20);
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(fieldOntPath)
                            .addComponent(fieldXmlAlgPath, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnLoadOnt, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE)
                            .addComponent(btnLoadXmlAlg, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnGenRAlg, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(btnGenSql, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)))
                .addGap(24, 24, 24))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnLoadXmlAlg)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnLoadOnt)
                            .addComponent(fieldOntPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(fieldXmlAlgPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnGenSql, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGenRAlg, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                .addContainerGap())
        );

        btnLoadXmlAlg.setText("...");
        btnLoadOnt.setText("...");

        menuFile.setText("Arquivo");

        jMenuItem1.setAction(actionMap.get("loadXqAlgAction")); // NOI18N
        menuFile.add(jMenuItem1);

        menuLoadOnt.setAction(actionMap.get("loadOntAction")); // NOI18N
        menuFile.add(menuLoadOnt);
        menuFile.add(jSeparator3);

        menuGenRelAlg.setText("Gerar álgebra relacional");
        menuFile.add(menuGenRelAlg);

        menuGenSql.setText("Gerar SQL");
        menuFile.add(menuGenSql);
        menuFile.add(jSeparator4);

        menuExit.setAction(actionMap.get("exit")); // NOI18N
        menuFile.add(menuExit);

        jMenuBar1.add(menuFile);

        menuHelp.setText("Ajuda");

        menuAbout.setText("Sobre");
        menuHelp.add(menuAbout);

        jMenuBar1.add(menuHelp);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnGenRAlgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenRAlgActionPerformed
    
    start();
    
}//GEN-LAST:event_btnGenRAlgActionPerformed
    
private void btnGenSqlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenSqlActionPerformed
    
    start();
    
}//GEN-LAST:event_btnGenSqlActionPerformed
    
private void fieldXmlAlgPathMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fieldXmlAlgPathMouseClicked
// TODO add your handling code here:
    loadXqAlgAction();
    
}//GEN-LAST:event_fieldXmlAlgPathMouseClicked
    
private void fieldOntPathMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fieldOntPathMouseClicked
// TODO add your handling code here:
    loadOntAction();
}//GEN-LAST:event_fieldOntPathMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                new MainWindow().setVisible(true);
            }
        });
    }
    
    public File loadXmlFile() {
        try {
            JFileChooser fc = new JFileChooser(path + "/examples");
            fc.setFileFilter(new FileFilter() {
                
                @Override
                public boolean accept(File f) {
                    if (f == null) {
                        return false;
                    }
                    if (f.isDirectory()) {
                        return true;
                    }
                    return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
                }
                
                @Override
                public String getDescription() {
                    return "Arquivos XML";
                }
            });
            int opt = fc.showOpenDialog(this);
            if (opt == JFileChooser.APPROVE_OPTION) {
                File f = fc.getSelectedFile();
                Logging.getInstance().log("Arquivo carregado com sucesso.");
                return f;
            } else {
                Logging.getInstance().log("Ação cancelada pelo usuário.");
                return null;
            }
        } catch (Exception e) {
            Logging.getInstance().log("Ocorreu um erro: " + e.getMessage());
            return null;
        }
    }
    
    @Action
    public void loadXqAlgAction() {
        Logging.getInstance().log("Carregar documento XML de álgebra XQuery.");
        xAlgFile = loadXmlFile();
        if (xAlgFile != null) {
            fieldXmlAlgPath.setText(xAlgFile.getName());
        }
    }
    
    @Action
    public void loadOntAction() {
        Logging.getInstance().log("Carregar documento XML das Equivalências entre XML's, Ontologia e Modelo Relacional.");
        equivFile = loadXmlFile();
        if (equivFile != null) {
            fieldOntPath.setText(equivFile.getName());
        }
    }
    
    @Action
    public void exitAction() {
        dispose();
        System.exit(0);
    }
    
    public void start() {
        if (xAlgFile == null) {
            JOptionPane.showConfirmDialog(this, "Você não selecionou um documento XML\nPor favor selecione o arquivo XML referente à álgebra XQuery.", "Atenção",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
            return;
        } else if (equivFile == null) {
            JOptionPane.showConfirmDialog(this, "Você não selecionou um documento XML\nPor favor selecione o arquivo XML referente às Equivalências.", "Atenção",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
            return;
        }

        // TODO: Validar documentos de entrada com um dtd ou xsd
        try {
            program = new Core(xAlgFile, equivFile);
//        tProgram = new Thread(program);
//        tProgram.start();
            program.run();
            String s = program.getOutput();

            //Logging.getInstance().log("Há!\n" + s, 3);
            
            txtLog.setText(s);
        } catch (Exception e) {
            Logging.getInstance().log("Erro ao processar o documento.\n" + e.getMessage(), 3);
        }
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGenRAlg;
    private javax.swing.JButton btnGenSql;
    private javax.swing.JButton btnLoadOnt;
    private javax.swing.JButton btnLoadXmlAlg;
    private javax.swing.JTextField fieldOntPath;
    private javax.swing.JTextField fieldXmlAlgPath;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JPopupMenu.Separator jSeparator4;
    private javax.swing.JMenuItem menuAbout;
    private javax.swing.JMenuItem menuExit;
    private javax.swing.JMenu menuFile;
    private javax.swing.JMenuItem menuGenRelAlg;
    private javax.swing.JMenuItem menuGenSql;
    private javax.swing.JMenu menuHelp;
    private javax.swing.JMenuItem menuLoadOnt;
    private javax.swing.JTextArea txtLog;
    // End of variables declaration//GEN-END:variables
}
